package com.myjava.annotation;


import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 查询结果字典翻译切面
 * @Project: datacenter-parent
 * @Author: chendongliang
 * @Date: 2018/8/22 17:52
 */
@Aspect
@Component
public class TranslateDictAspect {

    private final static Logger logger = LoggerFactory.getLogger(TranslateDictAspect.class);

    @Autowired
    TranslateService translateService;

    //@Pointcut("execution(* com.lishiots.cloud.datacenter.*.service.*.query*(..))")    //基于函数名的方式实现
//    @Pointcut("@annotation(com.lishiots.cloud.datacenter.kernel.annotation.TranslateDict)")   //基于注解的方式实现
    public void anyMethod(){
    }

    @Around(value = "anyMethod()")
    public Object doAspect(ProceedingJoinPoint pjp){
        logger.debug("----------------------------------字典切面----------------------------------");
        try {

            Object result = pjp.proceed();
            if(result != null ){
                logger.debug("----------------------------------字典切面--分页查询----------------------------------");
                if(result instanceof Pagination){
                    Pagination r = (Pagination) result ;
                    Object data = r.getData();
                    if(data != null
                            && data instanceof List
                            && ((List) data).size() > 0
                            && ((List) data).get(0) instanceof Translateable) {
                            translateService.translate((List) data);
                    }
                }else if(result instanceof RestfulMessage){
                    logger.debug("----------------------------------字典切面--ID查询/List查询----------------------------------");
                    RestfulMessage r = (RestfulMessage) result ;
                    Object data = r.getData();
                    if(data != null){
                        if(data instanceof Translateable){
                            translateService.translate((Translateable) data);
                        }else if(data instanceof List
                                  && ((List) data).size() > 0
                                  && ((List) data).get(0) instanceof Translateable){
                            translateService.translate((List) data);
                        }
                    }

                }
            }

            return result ;
        } catch (Throwable e) {
            logger.error("***************************************字典切面翻译异常****************************{}", e);
        }
        return null ;
    }
}
